package com.ruitu.ssmic.view;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.TextView;

import com.ruitu.ssmic.R;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class CountDownButton extends TextView {
    //倒计时的时间
    private long millisinfuture;
    //时间间隔
    private long countdowninterva;
//    private int normalColor;
//    private int countDownColor;

    //是否处于倒计时中
    private boolean isFinish;
    //倒计时
    private CountDownTimer countDownTimer;

    public CountDownButton(Context context) {
        this(context, null);
    }

    public CountDownButton(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CountDownButton, defStyleAttr, 0);
        millisinfuture = typedArray.getInt(R.styleable.CountDownButton_millisinfuture, 60000);
        countdowninterva = typedArray.getInt(R.styleable.CountDownButton_countdowninterva, 1000);
//        normalColor = typedArray.getColor(R.styleable.CountDownButton_normalColor, R.drawable.shape_get_code_btn_normal);
//        countDownColor = typedArray.getColor(R.styleable.CountDownButton_countDownColor, R.drawable.shape_get_code_btn);
        typedArray.recycle();
        isFinish = true;
        normalBackground();
        countDownTimer = new CountDownTimer(millisinfuture, countdowninterva) {
            @Override
            public void onTick(long millisUntilFinished) {
                isFinish = false;

                setText((Math.round((double) millisUntilFinished / 1000) - 1) + "秒");
                setEnabled(false);
//                setBackgroundResource(countDownColor);
            }

            @Override
            public void onFinish() {

                isFinish = true;
                normalBackground();
            }
        };
    }

    private void normalBackground() {
        setText("发送验证码");
//        setBackgroundResource(normalColor);
        setEnabled(true);
    }

    public boolean isFinish() {
        return isFinish;
    }

    public void cancle() {
        countDownTimer.cancel();
    }

    public void start() {
        countDownTimer.start();
    }
}
